package com.sky.service.user.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealMapper;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.pojo.Setmeal;
import com.sky.pojo.ShoppingCart;
import com.sky.service.user.ShoppingCartService;
import com.sky.vo.DishVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2024/10/16 14:28
 * @Version 1.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {

    private final ShoppingCartMapper shoppingCartMapper;
    private final DishMapper dishMapper;
    private final SetmealMapper setmealMapper;
    @Override
    public void add(ShoppingCartDTO dto) {
        //添加购物车，就是往数据库购物车表里面新增增数据
        //注意逻辑：已经存在的菜品，如果新增，那么只需要修改份数即可
        ShoppingCart shoppingCart = new ShoppingCart();
        //封装数据
        shoppingCart.setUserId(BaseContext.getCurrentId());
        shoppingCart.setDishFlavor(dto.getDishFlavor());
        shoppingCart.setCreateTime(LocalDateTime.now());
        //先查询购物车是否存在菜品或者套餐
        ShoppingCart existCart = shoppingCartMapper.getByDishIdOrSetMealId(dto.getDishId(), dto.getSetmealId(), BaseContext.getCurrentId());
        if(existCart != null){
            log.info("改菜品或者套餐已存在，修改数量即可");
            shoppingCartMapper.updateNumById(existCart.getNumber() + 1,existCart.getId());
            return;
        }

        shoppingCart.setNumber(1);

        //菜品的情况
        if(dto.getDishId() != null){
            DishVO dish = dishMapper.getDishById(dto.getDishId());
            shoppingCart.setName(dish.getName());
            shoppingCart.setImage(dish.getImage());
            shoppingCart.setAmount(dish.getPrice());
            shoppingCart.setDishId(dto.getDishId());
        }else{
            //套餐情况
            Setmeal setmeal = setmealMapper.getById(dto.getSetmealId());
            shoppingCart.setName(setmeal.getName());
            shoppingCart.setImage(setmeal.getImage());
            shoppingCart.setAmount(setmeal.getPrice());
            shoppingCart.setSetmealId(dto.getSetmealId());
        }

        shoppingCartMapper.insert(shoppingCart);
    }

    @Override
    public List<ShoppingCart> queryUserCarts() {
        return shoppingCartMapper.getByUserId(BaseContext.getCurrentId());
    }
}